package com.ys.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ys.constant.ShopCode;
import com.ys.exception.CastException;
import com.ys.mapper.GoodsMapper;
import com.ys.mapper.GoodsNumberLogMapper;
import com.ys.pojo.TradeGoods;
import com.ys.pojo.TradeGoodsNumberLog;
import com.ys.pojo.TradeOrder;
import com.ys.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, TradeGoods> implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsNumberLogMapper goodsNumberLogMapper;

    @Override
    public TradeGoods findGoodsById(TradeOrder order) {
        QueryWrapper<TradeGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TradeGoods::getGoodsId,order.getGoodsId());
        return goodsMapper.selectOne(queryWrapper);
    }

    @Override
    public Boolean reduceGoodsNum(TradeGoodsNumberLog goodsNumberLog) {
        if (goodsNumberLog == null ||
                goodsNumberLog.getGoodsNumber() == null ||
                goodsNumberLog.getOrderId() == null ||
                goodsNumberLog.getGoodsNumber() == null ||
                goodsNumberLog.getGoodsNumber().intValue() <= 0) {
            CastException.cast(ShopCode.SHOP_REQUEST_PARAMETER_VALID);
        }
        TradeGoods goods = goodsMapper.selectById(goodsNumberLog.getGoodsId());
        //库存不足
        if(goods.getGoodsNumber()<goodsNumberLog.getGoodsNumber()){
            //库存不足
            CastException.cast(ShopCode.SHOP_GOODS_NUM_NOT_ENOUGH);
        }
        //扣减库存
        UpdateWrapper<TradeGoods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(TradeGoods::getGoodsId,goodsNumberLog.getGoodsId()).set(TradeGoods::getGoodsNumber,goods.getGoodsNumber()-goodsNumberLog.getGoodsNumber());
        goodsMapper.update(goods, updateWrapper);

        //记录库存操作日志
        goodsNumberLog.setGoodsNumber(-(goodsNumberLog.getGoodsNumber()));
        goodsNumberLog.setLogTime(new Date());
        goodsNumberLogMapper.insert(goodsNumberLog);

        return ShopCode.SHOP_SUCCESS.getSuccess();
    }
}
